package com.cangxuan.app.ui.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.appcompat.app.ActionBar;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.MainActivity;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.entity.Order;
import com.cangxuan.app.entity.Registration;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.ui.collection.CollectionDetailActivity;
import com.cangxuan.app.ui.collection.OrderPayActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;

import java.io.File;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: 陈青石
 * Activity: 我的订单页面
 * Layout: activity_myorder
 */
public class MyOrderActivity extends BaseActivity {


    class MyOrderWaitAdapter extends BaseAdapter {

        private List<Order> orders;

        public MyOrderWaitAdapter(List<Order> orders) {
            this.orders = orders;
        }

        @Override
        public int getCount() {
            return orders.size();
        }

        @Override
        public Object getItem(int i) {
            return orders.get(i);
        }

        @Override
        public long getItemId(int i) {
            return orders.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            MyOrderWaitViewHolder viewHolder;
            if (view == null) {
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_myorder_waitpay_item, viewGroup, false);
                viewHolder = new MyOrderWaitViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (MyOrderWaitViewHolder) view.getTag();
            }
            Order order = orders.get(i);

            String goodsImagePath = "/data/data/" + getApplicationContext().getPackageName() + order.getImage();
            File imageFile = new File(goodsImagePath);
            if (imageFile.exists()) {
                viewHolder.waitPayImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
            } else {
                Thread thread = new Thread(() -> {
                    boolean result = HttpUtils.download(order.getImage(), goodsImagePath);
                    if (result) {
                        handler.post(() -> {
                            viewHolder.waitPayImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
                        });
                    }
                });
                thread.start();
            }

            viewHolder.waitPayName.setText(order.getName());
            viewHolder.waitPayTerm.setText("数量:" + order.getCount());
            viewHolder.waitPayCode.setText("NO." + order.getGoodsId());
            viewHolder.waitPayPrice.setText("￥" + order.getPrice());

            viewHolder.waitPayState.setText(order.getState());
            viewHolder.waitPayOrderCodeV.setText(String.valueOf(order.getId()));
            viewHolder.waitPayCreateTimeV.setText(order.getCreateTime().format(formatter));
            viewHolder.waitPayCancel.setOnClickListener(view1 -> {
                if (topIndex == 0) {
                    cancelOrderForm(order.getId());
                } else {
                    payCancelRegistration(order);
                }

            });
            viewHolder.waitPayGoPay.setOnClickListener(view2 -> {
                Intent intent = new Intent(getApplicationContext(), OrderPayActivity.class);
                intent.putExtra("topIndex", topIndex);
                intent.putExtra("comeFrom", topIndex);
                if (topIndex == 0) {
                    intent.putExtra("orderform", JSONObject.toJSONString(JSON.toJSON(order)));
                } else {
                    List<Order> orderList1 = new ArrayList<>();
                    orderList1.add(order);
                    intent.putExtra("orderform", (Serializable) orderList1);
                }
                System.out.println(order);
                intent.putExtra("sum", String.valueOf(order.getTransAmount()));
                startActivity(intent);

            });


            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class MyOrderWaitViewHolder {
            ImageView waitPayImg;
            TextView waitPayName;
            TextView waitPayTerm;
            TextView waitPayCode;
            TextView waitPayPrice;
            TextView waitPayState;
            TextView waitPayOrderCodeV;
            TextView waitPayCreateTimeV;
            Button waitPayCancel;
            Button waitPayGoPay;

            public MyOrderWaitViewHolder(View view) {
                this.waitPayImg = view.findViewById(R.id.waitpay_img);
                this.waitPayName = view.findViewById(R.id.waitpay_name);
                this.waitPayTerm = view.findViewById(R.id.waitpay_term);
                this.waitPayCode = view.findViewById(R.id.waitpay_code);
                this.waitPayPrice = view.findViewById(R.id.waitpay_price);
                this.waitPayState = view.findViewById(R.id.waitpay_state);
                this.waitPayOrderCodeV = view.findViewById(R.id.waitpay_ordercodeV);
                this.waitPayCreateTimeV = view.findViewById(R.id.waitpay_createtimeV);
                this.waitPayCancel = view.findViewById(R.id.waitpay_cancel);
                this.waitPayGoPay = view.findViewById(R.id.waitpay_goPay);
            }

        }

    }


    class MyOrderFinishAdapter extends BaseAdapter {

        private List<Order> orders;

        public MyOrderFinishAdapter(List<Order> orders) {
            this.orders = orders;
        }

        @Override
        public int getCount() {
            return orders.size();
        }

        @Override
        public Object getItem(int i) {
            return orders.get(i);
        }

        @Override
        public long getItemId(int i) {
            return orders.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            MyOrderFinishViewHolder viewHolder;
            if (view == null) {
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_myorder_finishpay_item, viewGroup, false);
                viewHolder = new MyOrderFinishViewHolder(view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (MyOrderFinishViewHolder) view.getTag();
            }
            Order order = orders.get(i);

            String goodsImagePath = "/data/data/" + getApplicationContext().getPackageName() + order.getImage();
            File imageFile = new File(goodsImagePath);
            if (imageFile.exists()) {
                viewHolder.finishPayImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
            } else {
                Thread thread = new Thread(() -> {
                    boolean result = HttpUtils.download(order.getImage(), goodsImagePath);
                    if (result) {
                        handler.post(() -> {
                            viewHolder.finishPayImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
                        });
                    }
                });
                thread.start();
            }


            viewHolder.finishPayName.setText(order.getName());
            viewHolder.finishPayTerm.setText("数量:" + order.getCount());
            viewHolder.finishPayCode.setText("NO." + order.getGoodsId());
            viewHolder.finishPayPrice.setText("￥" + order.getPrice());
            viewHolder.finishPayState.setText(order.getState());
            viewHolder.finishPayOrderCodeV.setText(String.valueOf(order.getId()));
            viewHolder.finishPayCreateTimeV.setText(order.getCreateTime().format(formatter));

            String date = order.getPayedTime() == null ? "已取消" : order.getPayedTime().format(formatter);

            viewHolder.finishPayPayTimeV.setText(date);

            if (index == 2) {
                viewHolder.finishPayState.setTextColor(Color.rgb(61, 178, 7));
            } else if (index == 3) {
                viewHolder.finishPayState.setTextColor(Color.rgb(229, 28, 35));
            }

            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class MyOrderFinishViewHolder {
            ImageView finishPayImg;
            TextView finishPayName;
            TextView finishPayTerm;
            TextView finishPayCode;
            TextView finishPayPrice;
            TextView finishPayState;
            TextView finishPayOrderCodeV;
            TextView finishPayCreateTimeV;
            TextView finishPayPayTimeV;

            public MyOrderFinishViewHolder(View view) {
                this.finishPayImg = view.findViewById(R.id.finishpay_img);
                this.finishPayName = view.findViewById(R.id.finishpay_name);
                this.finishPayTerm = view.findViewById(R.id.finishpay_term);
                this.finishPayCode = view.findViewById(R.id.finishpay_code);
                this.finishPayPrice = view.findViewById(R.id.finishpay_price);
                this.finishPayState = view.findViewById(R.id.finishpay_state);
                this.finishPayOrderCodeV = view.findViewById(R.id.finishpay_ordercodeV);
                this.finishPayCreateTimeV = view.findViewById(R.id.finishpay_createtimeV);
                this.finishPayPayTimeV = view.findViewById(R.id.finishpay_paytimeV);
            }

        }

    }

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    Button myOrderWaitPay;
    Button myOrderFinishPay;
    Button myOrderCancelPay;
    MyOrderFinishAdapter myOrderFinishAdapter;
    MyOrderWaitAdapter myOrderWaitAdapter;
    ListView myOrderListview;
    List<Order> orderList;
    ImageView back;
    Button collectionOrder;
    Button marketOrder;
    LinearLayout orderLoading;
    LinearLayout emptyText;
    static int index;

    static int topIndex;
    Map<String, String> header;
    Handler handler = new Handler();
    int goHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myorder);

        Intent intent1 = getIntent();
        goHome = intent1.getIntExtra("goHome", 0);
        topIndex = intent1.getIntExtra("topIndex", 0);
        index = intent1.getIntExtra("index", 2);

        header = new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_myorder_actionbar_background));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View views = inflater.inflate(R.layout.activity_myorder_actionbar, null);
        actionBar.setCustomView(views, lp);

        back = views.findViewById(R.id.button1);
        collectionOrder = views.findViewById(R.id.button2);
        marketOrder = views.findViewById(R.id.button3);
        back.setOnClickListener(view -> {
            if (goHome == 0) {
                finish();
            } else {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }


        });

        collectionOrder.setOnClickListener(view -> {
            if (topIndex != 0) {
                topIndex = 0;
                replaceTopBar();
                getOrderForm();
            }
        });
        marketOrder.setOnClickListener(view -> {
            if (topIndex != 1) {
                topIndex = 1;
                replaceTopBar();
                getOrderForm();
            }
        });


        myOrderWaitPay = findViewById(R.id.myorder_waitpay);
        myOrderFinishPay = findViewById(R.id.myorder_finishpay);
        myOrderCancelPay = findViewById(R.id.myorder_cancelpay);
        myOrderListview = findViewById(R.id.myorder_listview);
        orderLoading = findViewById(R.id.order_loading);
        emptyText = findViewById(R.id.empty_text);

        myOrderWaitPay.setOnClickListener(view -> {
            if (index != 1) {
                index = 1;
                replaceBar();
                getOrderForm();
            }
        });
        myOrderFinishPay.setOnClickListener(view -> {
            if (index != 2) {
                index = 2;
                replaceBar();
                getOrderForm();
            }
        });
        myOrderCancelPay.setOnClickListener(view -> {
            if (index != 3) {
                index = 3;
                replaceBar();
                getOrderForm();
            }
        });

        replaceTopBar();

        replaceBar();

        getOrderForm();

        myOrderListview.setOnItemClickListener((adapterView, view, i, l) -> {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), CollectionDetailActivity.class);
            intent.putExtra("goodsId", orderList.get(i).getGoodsId());
            intent.putExtra("isShow", 0);
            startActivity(intent);
        });


    }

    private void cancelOrderForm(int id) {
        orderLoading.setVisibility(View.VISIBLE);
        myOrderListview.setVisibility(View.GONE);
        emptyText.setVisibility(View.GONE);
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/orderform/cancel/" + id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    getOrderForm();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            } else {
                handler.post(() -> {
                    getOrderForm();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }

    private void payCancelRegistration(Order order) {
        List<Order> cancelList = new ArrayList<>();
        cancelList.add(order);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(cancelList));
        orderLoading.setVisibility(View.VISIBLE);
        myOrderListview.setVisibility(View.GONE);
        emptyText.setVisibility(View.GONE);
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.post("/api/registration/cancel", header, String.valueOf(array));
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    getOrderForm();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            } else {
                handler.post(() -> {
                    getOrderForm();
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }

    private void getOrderForm() {
        setAllButtonClickable(false);
        orderLoading.setVisibility(View.VISIBLE);
        myOrderListview.setVisibility(View.GONE);
        emptyText.setVisibility(View.GONE);
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/orderform/get/" + topIndex + "/" + index, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonArray = jsonResponse.getJSONArray("value");
                orderList = JSONObject.parseArray(jsonArray.toJSONString(), Order.class);
                handler.post(() -> {
                    orderLoading.setVisibility(View.GONE);
                    emptyText.setVisibility(View.GONE);
                    myOrderListview.setVisibility(View.VISIBLE);
                    setAllButtonClickable(true);
                    if (orderList.size() == 0) {
                        myOrderListview.setVisibility(View.GONE);
                        emptyText.setVisibility(View.VISIBLE);
                    } else {
                        if (index == 1) {
                            myOrderWaitAdapter = new MyOrderWaitAdapter(orderList);
                            myOrderListview.setAdapter(myOrderWaitAdapter);
                        } else {
                            myOrderFinishAdapter = new MyOrderFinishAdapter(orderList);
                            myOrderListview.setAdapter(myOrderFinishAdapter);
                        }
                    }

                });

            } else {
                handler.post(() -> {
                    orderLoading.setVisibility(View.GONE);
                    myOrderListview.setVisibility(View.VISIBLE);
                    setAllButtonClickable(true);
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }

    private void setAllButtonClickable(boolean click) {
        myOrderWaitPay.setClickable(click);
        myOrderFinishPay.setClickable(click);
        myOrderCancelPay.setClickable(click);
        collectionOrder.setClickable(click);
        marketOrder.setClickable(click);
    }

    private void replaceBar() {

        if (index == 1) {
            myOrderWaitPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_live));
            myOrderWaitPay.setTextColor(getResources().getColor(R.color.white));
            myOrderFinishPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderFinishPay.setTextColor(getResources().getColor(R.color.black));
            myOrderCancelPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderCancelPay.setTextColor(getResources().getColor(R.color.black));
        } else if (index == 2) {
            myOrderFinishPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_live));
            myOrderFinishPay.setTextColor(getResources().getColor(R.color.white));
            myOrderWaitPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderWaitPay.setTextColor(getResources().getColor(R.color.black));
            myOrderCancelPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderCancelPay.setTextColor(getResources().getColor(R.color.black));
        } else {
            myOrderCancelPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_live));
            myOrderCancelPay.setTextColor(getResources().getColor(R.color.white));
            myOrderFinishPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderFinishPay.setTextColor(getResources().getColor(R.color.black));
            myOrderWaitPay.setBackground(getResources().getDrawable(R.drawable.shape_mycollection_btn_normal));
            myOrderWaitPay.setTextColor(getResources().getColor(R.color.black));
        }
    }

    private void replaceTopBar() {

        if (topIndex == 0) {
            collectionOrder.setBackground(getResources().getDrawable(R.drawable.layer_list_myorder_actionbar_bottom));
            collectionOrder.setTextColor(Color.rgb(22, 132, 252));
            marketOrder.setBackground(null);
            marketOrder.setTextColor(getResources().getColor(R.color.black));

        } else if (topIndex == 1) {
            marketOrder.setBackground(getResources().getDrawable(R.drawable.layer_list_myorder_actionbar_bottom));
            marketOrder.setTextColor(Color.rgb(22, 132, 252));
            collectionOrder.setBackground(null);
            collectionOrder.setTextColor(getResources().getColor(R.color.black));
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderForm();
    }
}
